<template>
  <el-dialog
    title="地图服务配置"
    :visible.sync="visible"
    width="90%"
    :before-close="handleClose"
    class="map-config-dialog"
  >
    <div class="map-config-content">
      <!-- 上方配置区域 -->
      <div class="config-section">
        <div class="config-row">
          <div class="config-item">
            <label>地图类型：</label>
            <el-select
              v-model="mapConfig.mapType"
              placeholder="请选择"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in mapTypeDict"
                :key="index"
                :label="item.value"
                :value="item.key"
              />
            </el-select>
          </div>
        </div>

        <div class="config-row">
          <div class="config-item">
            <label>浅色地图：</label>
            <div class="service-input-group">
              <el-input 
                v-model="mapConfig.mapTintUrl" 
                placeholder="请输入地图服务地址"
                style="flex: 1;"
              />
                             <el-button 
                 type="primary" 
                 @click="handlePreview(mapConfig.mapTintUrl)"
                 :loading="previewLoading"
                 style="margin-left: 10px;"
               >
                 {{ previewLoading ? '加载中...' : '预览' }}
               </el-button>
            </div>
          </div>

          <div class="config-item">
            <label>深色地图：</label>
            <div class="service-input-group">
              <el-input 
                v-model="mapConfig.mapDarknessUrl" 
                placeholder="请输入地图服务地址"
                style="flex: 1;"
              />
                             <el-button 
                 type="primary" 
                 @click="handlePreview(mapConfig.mapDarknessUrl)"
                 :loading="previewLoading"
                 style="margin-left: 10px;"
               >
                 {{ previewLoading ? '加载中...' : '预览' }}
               </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 下方内容区域 -->
      <div class="content-section">
        <!-- 左侧字段别名表格 -->
        <div class="left-panel">
          <div class="panel-header">
            <h3>字段别名配置</h3>
            <!-- <el-button type="primary" size="small" @click="addFieldAlias">
              添加字段
            </el-button> -->
          </div>
          <div class="table-container">
            <el-table :data="fieldAliases" style="width: 100%" size="small">
              <el-table-column prop="url" label="图层名称" min-width="120">
                <template #default="{ row }">
                  <div>{{ row.url }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="originalName" label="字段名称" min-width="100">
                <template #default="{ row }">
                  <div>{{ row.originalName }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="actuallyName" label="字段别名" min-width="120">
                <template #default="{ row }">
                  <el-input v-model="row.actuallyName" placeholder="字段别名" />
                </template>
              </el-table-column>
              <el-table-column prop="orderIndex" label="排序">
                <template #default="{ row }">
                  <el-input v-model="row.orderIndex" placeholder="排序" type="number" />
                </template>
              </el-table-column>
              <!-- <el-table-column label="操作" width="80">
                <template #default="{ $index }">
                  <el-button 
                    type="text" 
                    size="small" 
                    @click="removeFieldAlias($index)"
                    style="color: #f56c6c;"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column> -->
            </el-table>
          </div>
        </div>

        <!-- 右侧地图预览 -->
        <div class="right-panel">
          <div class="panel-header">
            <h3>地图预览</h3>
          </div>
                     <div class="map-container">
             <MapboxMap
               :key="mapKey"
               :map-id="mapId"
               :center="mapCenter"
               :zoom="mapZoom"
               :base-map-config="baseMapConfig"
               @after-map-loaded="handleMapLoaded"
             />
           </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { Message } from 'element-ui'
import MapboxMap from '@/components/mapbox-map/MapboxMap.vue'
import axios from 'axios'
import { getLayerFieldsByLayerName } from '@/api/screen-management/indicator-management'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  }
})

const emits = defineEmits(['update:visible', 'submit'])

const mapTypeDict = ref([
  { key: '21', value: 'WMTS' },
  { key: '22', value: 'XYZ Tiles' },
  { key: '23', value: '矢量切片服务' },
  { key: '24', value: 'WMS' },
  { key: '25', value: 'ArcGIS Server' },
  { key: '26', value: 'SuperMap REST' },
  { key: '27', value: 'SuperMap Realspace' },
])

// 地图配置
const mapConfig = reactive({
  mapType: '',
  mapTintUrl: '',
  mapDarknessUrl: '',
  serviceUrl: ''
})

// 字段别名数据
const fieldAliases = ref([])

// 地图相关
const mapId = ref('map-config-preview')
const mapCenter = ref([106.49328310804757, 29.768499553618765])
const mapZoom = ref(12)
const baseMapConfig = ref({
  type: 'vector'
})
const previewLoading = ref(false)
const mapKey = ref(0) // 用于强制重新渲染地图组件
let mapInstance = null

// 监听弹窗显示状态
watch(() => props.visible, async (visible) => {
  if (visible) {
    
    // 先清空地图
    if (mapInstance) {
      clearMapService()
    }
    
    // 初始化数据
    initData()
    
    // 等待DOM更新
    await nextTick()
    
    // 强制重新加载地图组件
    await reloadMap()
    
    // 如果有URL，自动预览
    if (mapConfig.mapTintUrl || mapConfig.mapDarknessUrl) {
      handlePreview(mapConfig.mapTintUrl || mapConfig.mapDarknessUrl)
    }
  } else {
    if (mapInstance) {
      clearMapService()
    }
    // 重置地图实例
    mapInstance = null
  }
})


// 重新加载地图组件
const reloadMap = async () => {
  
  // 重置地图实例
  mapInstance = null
  
  // 更新mapKey强制重新渲染地图组件
  mapKey.value++
  
  // 等待地图组件重新渲染
  await nextTick()
  
  // 等待地图实例加载
  await new Promise(resolve => {
    const checkMapInstance = () => {
      if (mapInstance) {
        resolve()
      } else {
        setTimeout(checkMapInstance, 100)
      }
    }
    checkMapInstance()
  })
}

// 初始化数据
const initData = () => {
  // 清空地图配置
  mapConfig.serviceUrl = ''
  mapConfig.mapTintUrl = ''
  mapConfig.mapDarknessUrl = ''
  mapConfig.mapType = '23'
  
  // 清空字段别名数据
  fieldAliases.value = []
  
  // 如果有行数据，加载现有配置
  if (props.rowData && Object.keys(props.rowData).length > 0) {
    mapConfig.serviceUrl = props.rowData.mapUrl || ''
    mapConfig.mapTintUrl = props.rowData.mapTintUrl || ''
    mapConfig.mapDarknessUrl = props.rowData.mapDarknessUrl || ''
    mapConfig.mapType = props.rowData.mapType
    
    // 设置serviceUrl为第一个可用的URL
    if (mapConfig.mapTintUrl) {
      mapConfig.serviceUrl = mapConfig.mapTintUrl
    } else if (mapConfig.mapDarknessUrl) {
      mapConfig.serviceUrl = mapConfig.mapDarknessUrl
    }

    // 如果有字段配置，加载字段别名
    if (props.rowData.fieldJson) {
      try {
        // 检查fieldJson是否为有效的JSON字符串
        const fieldJsonStr = props.rowData.fieldJson.toString().trim()
        
        // 验证JSON格式
        if (fieldJsonStr && fieldJsonStr !== 'null' && fieldJsonStr !== 'undefined' && isValidJSON(fieldJsonStr)) {
          const fieldData = JSON.parse(fieldJsonStr)
          if (Array.isArray(fieldData)) {
            fieldAliases.value = fieldData.map(item => ({
              url: item.url || '',
              originalName: item.originalName || '',
              actuallyName: item.actuallyName || '',
              orderIndex: item.orderIndex || ''
            }))
          } else if (typeof fieldData === 'object' && fieldData !== null) {
            // 如果不是数组但是一个对象，尝试转换为数组格式
            console.warn('字段配置不是数组格式，尝试转换:', fieldData)
            fieldAliases.value = []
          }
        } else {
          console.warn('字段配置为空或无效的JSON格式:', props.rowData.fieldJson)
          fieldAliases.value = []
        }
      } catch (error) {
        console.error('解析字段配置失败:', error)
        console.error('原始数据:', props.rowData.fieldJson)
        // 如果解析失败，清空字段别名
        fieldAliases.value = []
      }
    }
  }
}

// 验证JSON格式
const isValidJSON = (str) => {
  try {
    JSON.parse(str)
    return true
  } catch (e) {
    return false
  }
}

// 添加字段别名
const addFieldAlias = () => {
  fieldAliases.value.push({ url: '', originalName: '', actuallyName: '', orderIndex: '' })
}

// 删除字段别名
const removeFieldAlias = (index) => {
  fieldAliases.value.splice(index, 1)
}

// 预览地图服务
const handlePreview = async (url) => {
  if (!mapConfig.mapType) {
    Message.warning('请选择地图类型')
    return
  }

  if (!url) {
    Message.warning('请输入地图服务地址')
    return
  }

  previewLoading.value = true
  try {
    if (!mapInstance) {
      await new Promise(resolve => {
        const checkMap = () => {
          if (mapInstance) {
            resolve()
          } else {
            setTimeout(checkMap, 100)
          }
        }
        checkMap()
      })
    }
    
    // 加载地图服务
    await loadMapService(url)
    Message.success('预览加载成功')
  } catch (error) {
    Message.error('预览加载失败')
  } finally {
    previewLoading.value = false
  }
}

const clearMapService = () => {
  if (!mapInstance) return;

  try {
    // 复制当前图层列表，避免边删边遍历出错
    const layers = [...mapInstance.getStyle().layers];
    const sourcesToRemove = new Set();
    
    // 从后往前删除图层，避免索引问题
    for (let i = layers.length - 1; i >= 2; i--) {
      const layer = layers[i];
      const { id: layerId, source: sourceId } = layer;

      // 只删非底图的图层和source
      if (mapInstance.getLayer(layerId) && sourceId && sourceId !== 'composite') {
        try {
          mapInstance.removeLayer(layerId);
          sourcesToRemove.add(sourceId);
        } catch (err) {
          console.warn(`移除图层 ${layerId} 失败:`, err);
        }
      }
    }

    // 删掉对应 source
    sourcesToRemove.forEach(sourceId => {
      try {
        if (mapInstance.getSource(sourceId)) {
          mapInstance.removeSource(sourceId);
        }
      } catch (err) {
        console.warn(`移除数据源 ${sourceId} 失败:`, err);
      }
    });

  } catch (error) {
    console.error('清除地图服务失败:', error);
  }
};

// 加载地图服务 - 根据地图类型选择不同的加载方式
const loadMapService = async (url) => {
  if (!mapInstance || !url) {
    return
  }

  try {
    clearMapService()
    
    switch (mapConfig.mapType) {
      case '21': // WMTS
        await loadWMTSService(url)
        break
      case '22': // XYZ Tiles
        await loadXYZTilesService(url)
        break
      case '23': // 矢量切片服务
        await loadVectorTileService(url)
        break
      case '24': // WMS
        await loadWMSService(url)
        break
      case '25': // ArcGIS Server
        await loadArcGISService(url)
        break
      case '26': // SuperMap REST
        await loadSuperMapRESTService(url)
        break
      case '27': // SuperMap Realspace
        await loadSuperMapRealspaceService(url)
        break
      default:
        Message.error('不支持的地图类型')
        throw new Error('不支持的地图类型')
    }
    
  } catch (error) {
    Message.error('加载地图服务失败')
    throw error
  }
}

// WMTS服务加载
const loadWMTSService = async (url) => {
  try {
    // 解析WMTS服务URL，获取图层信息
    const layerId = `wmts-layer-${Date.now()}`
    const sourceId = `wmts-source-${Date.now()}`
    
    // 添加WMTS源
    mapInstance.addSource(sourceId, {
      type: 'raster',
      tiles: [url],
      tileSize: 256
    })
    
    // 添加WMTS图层
    mapInstance.addLayer({
      id: layerId,
      type: 'raster',
      source: sourceId,
      paint: {
        'raster-opacity': 0.8
      }
    })
    
    // 跳转到默认位置
    await flyToDefaultLocation()
    
    // 更新字段别名
    await updateFieldAliases([{ id: layerId }])
    
  } catch (error) {
    console.error('WMTS服务加载失败:', error)
    throw error
  }
}

// XYZ Tiles服务加载
const loadXYZTilesService = async (url) => {
  try {
    const layerId = `xyz-layer-${Date.now()}`
    const sourceId = `xyz-source-${Date.now()}`
    
    // 添加XYZ源
    mapInstance.addSource(sourceId, {
      type: 'raster',
      tiles: [url],
      tileSize: 256
    })
    
    // 添加XYZ图层
    mapInstance.addLayer({
      id: layerId,
      type: 'raster',
      source: sourceId,
      paint: {
        'raster-opacity': 0.8
      }
    })
    
    await flyToDefaultLocation()
    await updateFieldAliases([{ id: layerId }])
    
  } catch (error) {
    console.error('XYZ Tiles服务加载失败:', error)
    throw error
  }
}

// 矢量切片服务加载（原有的TileJSON方式）
const loadVectorTileService = async (url) => {
  try {
    // 获取TileJSON配置
    const response = await axios.get(url)
    const tileJSON = response.data
    
    // 批量添加源
    Object.keys(tileJSON.sources).forEach((sourceKey) => {
      if (!mapInstance.getSource(sourceKey)) {
        mapInstance.addSource(sourceKey, tileJSON.sources[sourceKey])
      }
    })
    
    // 批量添加图层
    tileJSON.layers.forEach((layer) => {
      if (!mapInstance.getLayer(layer.id)) {
        mapInstance.addLayer(layer)
      }
    })

    // 跳转到数据范围并等待完成
    if (tileJSON.center) {
      await new Promise(resolve => {
        mapInstance.flyTo({
          center: tileJSON.center,
          zoom: tileJSON.zoom || 12,
          duration: 1000
        })
        
        // 监听地图移动完成事件
        const onMoveEnd = () => {
          mapInstance.off('moveend', onMoveEnd)
          resolve()
        }
        mapInstance.on('moveend', onMoveEnd)
      })
    }

    // 等待图层渲染完成后更新字段别名表格
    await new Promise(resolve => {
      setTimeout(async () => {
        await updateFieldAliases(tileJSON.layers)
        resolve()
      }, 1500)
    })
    
  } catch (error) {
    console.error('矢量切片服务加载失败:', error)
    throw error
  }
}

// WMS服务加载
const loadWMSService = async (url) => {
  try {
    const layerId = `wms-layer-${Date.now()}`
    const sourceId = `wms-source-${Date.now()}`
    
    // 解析WMS URL，获取图层参数
    const urlObj = new URL(url)
    const wmsLayers = urlObj.searchParams.get('layers') || 'default'
    
    // 添加WMS源
    mapInstance.addSource(sourceId, {
      type: 'raster',
      tiles: [url],
      tileSize: 256
    })
    
    // 添加WMS图层
    mapInstance.addLayer({
      id: layerId,
      type: 'raster',
      source: sourceId,
      paint: {
        'raster-opacity': 0.8
      }
    })
    
    await flyToDefaultLocation()
    await updateFieldAliases([{ id: layerId }], { wmsLayers })
    
  } catch (error) {
    console.error('WMS服务加载失败:', error)
    throw error
  }
}

// ArcGIS Server服务加载
const loadArcGISService = async (url) => {
  try {
    // 获取ArcGIS服务信息
    const serviceUrl = url.replace('/MapServer', '')
    const infoUrl = `${serviceUrl}/MapServer?f=json`
    
    const response = await axios.get(infoUrl)
    const serviceInfo = response.data
    
    const layerId = `arcgis-layer-${Date.now()}`
    const sourceId = `arcgis-source-${Date.now()}`
    
    // 添加ArcGIS源
    mapInstance.addSource(sourceId, {
      type: 'raster',
      tiles: [`${url}/tile/{z}/{y}/{x}`],
      tileSize: 256
    })
    
    // 添加ArcGIS图层
    mapInstance.addLayer({
      id: layerId,
      type: 'raster',
      source: sourceId,
      paint: {
        'raster-opacity': 0.8
      }
    })
    
    await flyToDefaultLocation()
    await updateFieldAliases([{ id: layerId }], { serviceInfo })
    
  } catch (error) {
    console.error('ArcGIS服务加载失败:', error)
    throw error
  }
}

// SuperMap REST服务加载
const loadSuperMapRESTService = async (url) => {
  try {
    const layerId = `supermap-rest-layer-${Date.now()}`
    const sourceId = `supermap-rest-source-${Date.now()}`
    
    // 添加SuperMap REST源
    mapInstance.addSource(sourceId, {
      type: 'raster',
      tiles: [`${url}/tileImage.png?width=256&height=256&x={x}&y={y}&z={z}`],
      tileSize: 256
    })
    
    // 添加SuperMap REST图层
    mapInstance.addLayer({
      id: layerId,
      type: 'raster',
      source: sourceId,
      paint: {
        'raster-opacity': 0.8
      }
    })
    
    await flyToDefaultLocation()
    await updateFieldAliases([{ id: layerId }])
    
  } catch (error) {
    console.error('SuperMap REST服务加载失败:', error)
    throw error
  }
}

// SuperMap Realspace服务加载
const loadSuperMapRealspaceService = async (url) => {
  try {
    const layerId = `supermap-realspace-layer-${Date.now()}`
    const sourceId = `supermap-realspace-source-${Date.now()}`
    
    // 添加SuperMap Realspace源
    mapInstance.addSource(sourceId, {
      type: 'raster',
      tiles: [`${url}/tile/{z}/{y}/{x}`],
      tileSize: 256
    })
    
    // 添加SuperMap Realspace图层
    mapInstance.addLayer({
      id: layerId,
      type: 'raster',
      source: sourceId,
      paint: {
        'raster-opacity': 0.8
      }
    })
    
    await flyToDefaultLocation()
    await updateFieldAliases([{ id: layerId }])
    
  } catch (error) {
    console.error('SuperMap Realspace服务加载失败:', error)
    throw error
  }
}

// 跳转到默认位置
const flyToDefaultLocation = async () => {
  await new Promise(resolve => {
    mapInstance.flyTo({
      center: mapCenter.value,
      zoom: mapZoom.value,
      duration: 1000
    })
    
    const onMoveEnd = () => {
      mapInstance.off('moveend', onMoveEnd)
      resolve()
    }
    mapInstance.on('moveend', onMoveEnd)
  })
}

// 统一的字段别名更新逻辑
const updateFieldAliases = async (layers, additionalParams = {}) => {
  let newFieldAliases = []
  const layerNames = []
  
  // 第一步：收集图层名称
  for (const layer of layers) {
    layerNames.push(layer.id)
  }
  
  if (layerNames.length > 0) {
    try {
      // 第二步：通过getLayerFieldsByLayerName获取基础字段数据
      const allFields = await getLayerFieldsByLayerName(layerNames)
      newFieldAliases = allFields.data || []
      
      // 第三步：以allFields.data为基准，检查每个图层字段
      if (allFields && allFields.data) {
        // 遍历每个图层的字段
        for (const layer of layers) {
          // 根据地图类型调用不同的getLayerFields方法
          const layerFields = await getLayerFieldsByType(layer.id, layer, additionalParams)
          
          if (layerFields && layerFields.length > 0) {
            layerFields.forEach(field => {
              const existingField = allFields.data.find(item => 
                item.url === layer.id && item.originalName === field
              )
              
              // 如果allFields.data中没有这个字段，则叠加到newFieldAliases中
              if (!existingField) {
                newFieldAliases.push({
                  url: layer.id,
                  originalName: field,
                  actuallyName: field,
                  orderIndex: 0
                })
              }
            })
          }
        }
      }
    } catch (error) {
      console.error('获取图层字段数据失败:', error)
    }
  }
  
  // 第四步：赋值给fieldAliases.value
  fieldAliases.value = newFieldAliases
}

// 根据地图类型获取图层字段信息
const getLayerFieldsByType = async (layerId, layer, additionalParams = {}) => {
  switch (mapConfig.mapType) {
    case '21': // WMTS
      return await getLayerFieldsForWMTS(layerId, layer, additionalParams)
    case '22': // XYZ Tiles
      return await getLayerFieldsForXYZ(layerId, layer, additionalParams)
    case '23': // 矢量切片服务
      return await getLayerFieldsForVectorTile(layerId, layer, additionalParams)
    case '24': // WMS
      return await getLayerFieldsForWMS(layerId, layer, additionalParams)
    case '25': // ArcGIS Server
      return await getLayerFieldsForArcGIS(layerId, layer, additionalParams)
    case '26': // SuperMap REST
      return await getLayerFieldsForSuperMapREST(layerId, layer, additionalParams)
    case '27': // SuperMap Realspace
      return await getLayerFieldsForSuperMapRealspace(layerId, layer, additionalParams)
    default:
      return []
  }
}

// WMTS图层字段获取
const getLayerFieldsForWMTS = async (layerId, layer, additionalParams) => {
  try {
    // WMTS通常是栅格图层，没有字段信息
    // 但可以通过WMTS GetFeatureInfo获取属性信息
    if (!mapInstance) return []
    
    // 尝试通过GetFeatureInfo获取字段信息
    const features = mapInstance.queryRenderedFeatures({
      layers: [layerId]
    })
    
    if (features.length > 0) {
      const firstFeature = features[0]
      if (firstFeature && firstFeature.properties) {
        return Object.keys(firstFeature.properties)
      }
    }
    
    // 如果没有获取到字段，返回默认字段
    return ['WMTS图层']
  } catch (error) {
    console.error('WMTS图层字段获取失败:', error)
    return ['WMTS图层']
  }
}

// XYZ Tiles图层字段获取
const getLayerFieldsForXYZ = async (layerId, layer, additionalParams) => {
  try {
    // XYZ Tiles通常是栅格图层，没有字段信息
    if (!mapInstance) return []
    
    const features = mapInstance.queryRenderedFeatures({
      layers: [layerId]
    })
    
    if (features.length > 0) {
      const firstFeature = features[0]
      if (firstFeature && firstFeature.properties) {
        return Object.keys(firstFeature.properties)
      }
    }
    
    return ['XYZ图层']
  } catch (error) {
    console.error('XYZ Tiles图层字段获取失败:', error)
    return ['XYZ图层']
  }
}

// 矢量切片图层字段获取（原有的方法）
const getLayerFieldsForVectorTile = async (layerId, layer, additionalParams) => {
  if (!mapInstance) return []
  
  try {
    const features = mapInstance.queryRenderedFeatures({
      layers: [layerId]
    })
    
    if (features.length > 0) {
      const firstFeature = features[0]
      if (firstFeature && firstFeature.properties) {
        const fields = Object.keys(firstFeature.properties)
        return fields
      }
    }
    return []
  } catch (error) {
    console.error('获取图层字段失败:', error)
    return []
  }
}

// WMS图层字段获取
const getLayerFieldsForWMS = async (layerId, layer, additionalParams) => {
  try {
    // WMS可以通过GetFeatureInfo获取字段信息
    if (!mapInstance) return []
    
    const features = mapInstance.queryRenderedFeatures({
      layers: [layerId]
    })
    
    if (features.length > 0) {
      const firstFeature = features[0]
      if (firstFeature && firstFeature.properties) {
        return Object.keys(firstFeature.properties)
      }
    }
    
    // 如果没有获取到字段，使用WMS图层名称
    const wmsLayers = additionalParams.wmsLayers || 'default'
    return [`WMS图层: ${wmsLayers}`]
  } catch (error) {
    console.error('WMS图层字段获取失败:', error)
    return ['WMS图层']
  }
}

// ArcGIS Server图层字段获取
const getLayerFieldsForArcGIS = async (layerId, layer, additionalParams) => {
  try {
    const serviceInfo = additionalParams.serviceInfo
    const fields = []
    
    if (serviceInfo && serviceInfo.layers) {
      serviceInfo.layers.forEach(layerInfo => {
        if (layerInfo.fields) {
          layerInfo.fields.forEach(field => {
            fields.push(field.name)
          })
        }
      })
    }
    
    if (fields.length === 0) {
      fields.push('ArcGIS图层')
    }
    
    return fields
  } catch (error) {
    console.error('ArcGIS图层字段获取失败:', error)
    return ['ArcGIS图层']
  }
}

// SuperMap REST图层字段获取
const getLayerFieldsForSuperMapREST = async (layerId, layer, additionalParams) => {
  try {
    if (!mapInstance) return []
    
    const features = mapInstance.queryRenderedFeatures({
      layers: [layerId]
    })
    
    if (features.length > 0) {
      const firstFeature = features[0]
      if (firstFeature && firstFeature.properties) {
        return Object.keys(firstFeature.properties)
      }
    }
    
    return ['SuperMap REST图层']
  } catch (error) {
    console.error('SuperMap REST图层字段获取失败:', error)
    return ['SuperMap REST图层']
  }
}

// SuperMap Realspace图层字段获取
const getLayerFieldsForSuperMapRealspace = async (layerId, layer, additionalParams) => {
  try {
    if (!mapInstance) return []
    
    const features = mapInstance.queryRenderedFeatures({
      layers: [layerId]
    })
    
    if (features.length > 0) {
      const firstFeature = features[0]
      if (firstFeature && firstFeature.properties) {
        return Object.keys(firstFeature.properties)
      }
    }
    
    return ['SuperMap Realspace图层']
  } catch (error) {
    console.error('SuperMap Realspace图层字段获取失败:', error)
    return ['SuperMap Realspace图层']
  }
}

// 获取图层字段信息（已废弃，使用getLayerFieldsByType替代）
const getLayerFields = async (layerId, sourceLayer) => {
  console.warn('getLayerFields方法已废弃，请使用getLayerFieldsByType')
  return await getLayerFieldsForVectorTile(layerId, { 'source-layer': sourceLayer })
}

// 地图加载完成回调
const handleMapLoaded = (mapId, map) => {
  mapInstance = map
  
  // 等待地图样式加载完成
  map.on('style.load', () => {
    console.log('地图样式加载完成')
  })
}

// 关闭弹窗
const handleClose = () => {
  // 清空数据
  mapConfig.serviceUrl = ''
  mapConfig.mapTintUrl = ''
  mapConfig.mapDarknessUrl = ''
  mapConfig.mapType = ''
  fieldAliases.value = []
  mapInstance = null
  previewLoading.value = false
  
  emits('update:visible', false)
}

// 保存配置
const handleSave = () => {
  // 验证必填项
  if (!mapConfig.serviceUrl) {
    Message.warning('请输入地图服务地址')
    return
  }

  // 过滤空字段
  const validFieldAliases = fieldAliases.value.filter(
    item => item.actuallyName && item.actuallyName.trim()
  )

  const configData = {
    indexId: props.rowData.pkid,
    mapTintUrl: mapConfig.mapTintUrl,
    mapDarknessUrl: mapConfig.mapDarknessUrl,
    mapType: mapConfig.mapType,
    fieldList: validFieldAliases
  }

  emits('submit', configData)
  handleClose()
}
</script>

<style scoped lang="scss">
.map-config-dialog {
  .map-config-content {
    height: 70vh;
    display: flex;
    flex-direction: column;
  }

  .config-section {
    padding: 20px;
    border-bottom: 1px solid #ebeef5;
    background: #fafafa;

    .config-row {
      display: flex;
      gap: 20px;
      align-items: center;
      margin-bottom: 10px;

      .config-item {
        flex: 1;
        display: flex;
        align-items: center;
        gap: 10px;

        label {
          white-space: nowrap;
          font-weight: 500;
          color: #606266;
        }

        .service-input-group {
          display: flex;
          align-items: center;
          flex: 1;
        }
      }
    }
  }

  .content-section {
    flex: 1;
    display: flex;
    gap: 20px;
    padding: 20px;
    overflow: hidden;

    .left-panel {
      width: 45%;
      display: flex;
      flex-direction: column;
      border: 1px solid #ebeef5;
      border-radius: 4px;

      .panel-header {
        padding: 15px;
        border-bottom: 1px solid #ebeef5;
        background: #fafafa;
        display: flex;
        justify-content: space-between;
        align-items: center;

        h3 {
          margin: 0;
          font-size: 16px;
          color: #303133;
        }
      }

      .table-container {
        flex: 1;
        overflow: auto;
        padding: 15px;
      }
    }

    .right-panel {
      flex: 1;
      display: flex;
      flex-direction: column;
      border: 1px solid #ebeef5;
      border-radius: 4px;

      .panel-header {
        padding: 15px;
        border-bottom: 1px solid #ebeef5;
        background: #fafafa;

        h3 {
          margin: 0;
          font-size: 16px;
          color: #303133;
        }
      }

      .map-container {
        flex: 1;
        position: relative;
        overflow: hidden;
        min-height: 400px;

        .mapbox-map {
          height: 100%;
          width: 100%;
        }
      }
    }
  }

  .dialog-footer {
    text-align: right;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .map-config-dialog {
    .content-section {
      flex-direction: column;

      .left-panel {
        width: 100%;
        height: 200px;
      }

      .right-panel {
        height: 300px;
      }
    }
  }
}
</style>
